package com.gitee.fastmybatis.core.ext.transaction;

import com.gitee.fastmybatis.core.MybatisContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 事务处理
 *
 * @author thc
 */
public class TransactionTemplateManager {
    private static final Map<String, AliasTransactionTemplate> TRANSACTION_TEMPLATE_MAP = new HashMap<>();

    private static final String MAIN_ALIAS = MybatisContext.MAIN_DS_ALIAS;

    private TransactionTemplateManager() {
    }

    public static void addTransactionTemplate(AliasTransactionTemplate transactionTemplate) {
        TRANSACTION_TEMPLATE_MAP.put(transactionTemplate.getDbAlias(), transactionTemplate);
    }

    public static void addMainTransactionManager(PlatformTransactionManager transactionManager) {
        AliasTransactionTemplate transactionTemplate = new AliasTransactionTemplate(MAIN_ALIAS, transactionManager);
        TransactionTemplateManager.addTransactionTemplate(transactionTemplate);
    }

    /**
     * 获取数据源别名对应的TransactionTemplate
     *
     * @param dbAlias 数据源别名
     * @return 返回TransactionTemplate
     */
    public static TransactionTemplate getTransactionTemplate(String dbAlias) {
        AliasTransactionTemplate aliasTransactionTemplate = TRANSACTION_TEMPLATE_MAP.get(dbAlias);
        if (aliasTransactionTemplate == null) {
            return TRANSACTION_TEMPLATE_MAP.get(MAIN_ALIAS);
        }
        return aliasTransactionTemplate;
    }


}
